package com.jwds.digital.bios.business.service.service.flow.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jwds.digital.bios.business.core.infrastructure.dto.flow.FlowBasicReqDTO;
import com.jwds.digital.bios.business.core.infrastructure.entity.flow.FlowBasic;
import com.jwds.digital.bios.business.core.infrastructure.mapper.flow.FlowBasicMapper;

import com.jwds.digital.bios.business.core.infrastructure.vo.feign.FlowBasicRespVO;
import com.jwds.digital.bios.business.service.service.flow.IFlowBasicService;
import com.jwds.tdc.framework.application.lib.BaseResponse;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;

/**
 * @Description FlowBasicServiceImpl
 * @Author xiao  xun
 * @Date 2024-12-12
 */
@Service
public class FlowBasicServiceImpl extends ServiceImpl<FlowBasicMapper, FlowBasic> implements IFlowBasicService {
    @Resource
    private  FlowBasicMapper flowBasicMapper;
    @Override
    public List<FlowBasicRespVO> list(FlowBasicReqDTO reqDto) {
        return flowBasicMapper.queryList(reqDto);
    }

    @Override
    public Map<String, Map<String, BigDecimal>> getBeltInfoById(Long id) {
        FlowBasicRespVO flowBasic = flowBasicMapper.searchById(id);
//        FlowBasic flowBasic = this.selectById(id);
        if (flowBasic == null) {
            throw new RuntimeException("FlowBasic not found for ID: " + id);
        }

        String flowName = flowBasic.getFlowName();
        BigDecimal flowDistance = flowBasic.getFlowDistance();
        BigDecimal flowRatedPower = flowBasic.getFlowRatedPower();

        Map<String, Map<String, BigDecimal>> beltInfo = new HashMap<>();

        StringTokenizer st = new StringTokenizer(flowName, "_");
        int totalBelts = st.countTokens(); // 在循环前计算总的皮带数量

        while (st.hasMoreTokens()) {
            String beltName = st.nextToken();
            Map<String, BigDecimal> beltDetails = new HashMap<>();
            beltDetails.put("length", calculateBeltLength(beltName, flowDistance, totalBelts));
            beltDetails.put("power", calculateBeltPower(beltName, flowRatedPower, totalBelts));
            beltInfo.put(beltName, beltDetails);
        }

        return beltInfo;
    }
    private BigDecimal calculateBeltLength(String beltName, BigDecimal totalLength, int totalBelts) {
        // 假设每条皮带的长度均等分配
        return totalLength.divide(BigDecimal.valueOf(totalBelts), 2, BigDecimal.ROUND_HALF_UP);
    }

    private BigDecimal calculateBeltPower(String beltName, BigDecimal totalPower, int totalBelts) {
        // 假设每条皮带的额定功率均等分配
        return totalPower.divide(BigDecimal.valueOf(totalBelts), 2, BigDecimal.ROUND_HALF_UP);
    }


}
